# -*- coding:UTF-8 -*-
import os
import socket
import time
import requests
import MySQLdb
from flask import json
from MessageAnalysis import*
from obdMessageAnalysis import*
from hangbiaoMessageAnalysis import*

RPC_URL='http://139.217.19.225/platform/res/rpc.do'
MYSQL_USERNAME=os.environ.get('MYSQL_USERNAME')
MYSQL_PASSWORD=os.environ.get('MYSQL_PASSWORD')

def query_sn(dev_id):
    conn=MySQLdb.connect(host='172.10.11.6',user=MYSQL_USERNAME,passwd=MYSQL_PASSWORD,db='sync_with_ac',port=3306)
    cur=conn.cursor()
    mysql="select dev_sn from dev_info where dev_id=%s" % dev_id
    try:
        query_result=cur.execute(mysql)
        dev_sn=cur.fetchall()
        dev_sn=dev_sn[0][0]
        #print "dev_sn:%s" % dev_sn
        return dev_sn
    except:
        return {'NotFound':True}
    finally:
        cur.close()
        conn.close()

def get_free_tcp_port():
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.bind(('', 0))
    addr, port = tcp.getsockname()
    tcp.close()
    return port

def check_online(sn):
    if len(sn) == 7:
        sn=query_sn(sn)
    if 'NotFound' in sn:
        return {'ret':False, 'val':'NotFound'}
    req={'method':'list', 'param':sn}
    r=requests.post(RPC_URL, data=req) 
    #http://139.217.19.225/platform/res/rpc.do?method=list&param=7051d2
    if r.status_code!=200:
        return {'ret':False, 'val':'ERROR'}
    v=r.text.encode('utf-8').strip().split(',') #7051d2,1,贵AA3453 -> ['7051d2',1,'贵AA3453']
    if len(v)==3 and v[1]=='1':
        return {'ret':True, 'val':'ONLINE'}
    return {'ret':False, 'val':'OFFLINE'}

def exec_command(sn, cmd):
    if len(sn) == 7:
        sn=query_sn(sn)
    r=check_online(sn) #{'ret':True, 'val':'ONLINE'}
    if 'NotFound' in sn:
        return {'ret':False, 'val':'NotFound'}
    if r['ret']!=True:
        return r

    param={'sn':sn, 'script':cmd} #json_param={"sn": "7051d2", "script": "uptime"}
    req={'method':'shell','param':json.dumps(param)}
    current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print ("[BaseDebug]" + ' %s' + ' SN:' + '%s' + ' CMD:' + '%s')  %(current_time,sn,cmd)
    r=requests.post(RPC_URL,data=req)
    #curl -d 'method=shell&param={"sn":"7051d2","script":"uptime"}' http://139.217.19.225/platform/res/rpc.do
    ret=r.text.encode('utf-8')
    #if 'ERROR:' in ret:
    #    return {'ret':False, 'val':'ERROR'}
    return {'ret':True, 'val':ret} #

def exec_analyse(pro_id,pro_data):#8900,7e8900.....7e
    proresult=MessageAnalysis() #实例化对象
    #print "消息ID:%s 数据:%s" %(pro_id,pro_data)
    finalresult= proresult.doGet(pro_id,pro_data)
    print "finalresult"
    return {"val":finalresult}
def exec_analyse_17691(pro_id,pro_data):#8900,7e8900.....7e
    proresult=obdMessageAnalysis() #实例化对象
    #print "消息ID:%s 数据:%s" %(pro_id,pro_data)
    finalresult= proresult.doGet(pro_id,pro_data)
    print "finalresult"
    return {"val":finalresult}
def exec_analyse_hangbiao(pro_id,pro_data):#8900,7e8900.....7e
    proresult=hangbiaoMessageAnalysis() #实例化对象
    #print "消息ID:%s 数据:%s" %(pro_id,pro_data)
    finalresult= proresult.doGet(pro_id,pro_data)
    print "finalresult"
    return {"val":finalresult}
